<?php

namespace App\Jobs;

use App\Models\Article;
use App\Models\Subscribe;
use App\Services\PublishTemplateService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ArticleStarSubscribe implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $article_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($article_id)
    {
        $this->article_id = $article_id;
    }

    /**
     * Execute the job.
     * @link https://shimo.im/mindmaps/y6ydprxxxJKCggPx/
     * @return void
     */
    public function handle()
    {
        $field = ['nickname', 'openid'];
        $info = Article::withCertain('user', $field)->find($this->article_id);
        if (!$info)
            return;

        $subscribe = Subscribe::where('user_id', $info->user_id)->where('template_id', Subscribe::TEMPLATE_ARTICLE_STAR)->orderBy('id', 'asc')->first();
        if ($subscribe)
            $subscribe->delete();

        $service = new PublishTemplateService();
        $service->articleStar($info->user->openid, $info->title, $info->id, $info->type);
    }
}
